<template>
  <div class="data-transfer-wrapper">
    <el-steps
      :space="200"
      class="transfer-step"
      :active="currentIndex"
      finish-status="success"
    >
      <el-step title="上传文件"></el-step>
      <el-step title="设置映射关系"></el-step>
      <el-step title="完成导入"></el-step>
    </el-steps>
    <el-form
      class="transfer-form"
      :model="ruleForm"
      :rules="rules"
      :inline="false"
      ref="ruleForm"
      label-width="120px"
    >
      <div class="content" v-if="currentIndex === 0">
        <el-form-item label="数据类型" prop="data_type">
          <el-select v-model="ruleForm.data_type" placeholder="请选择文件类型">
            <el-option
              v-for="item in typeData"
              :label="item.label"
              :value="item.val * 1"
              :key="item.val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导入文件" prop="file_url" ref="imgRef1">
          <UploadLink
            :limit="1"
            :onExceed="handleExceed"
            :files.sync="ruleForm.file_url"
          ></UploadLink>
        </el-form-item>
      </div>
      <div class="content" v-if="currentIndex === 1">
        <el-table :data="tableData.match_result" style="width: 100%">
          <el-table-column prop="field_description" label="原字段" width="150">
          </el-table-column>
          <el-table-column prop="field_name" label="映射字段" width="150">
            <template slot-scope="scope">
              <el-select
                :disabled="scope.row.disableSelect"
                v-model="scope.row['field_name']"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="item in tableData.local_fields"
                  :label="item.field_description"
                  :value="item.field_name"
                  :key="item.field_name"
                  :disabled="usedNames.includes(item.field_name)"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="field_name" label="使用新字段">
            <template slot-scope="scope">
              <el-switch
                @change="(val) => handleChangeUseNew(val, scope.row)"
                v-model="scope.row.is_new_field"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
              <el-input
                style="width: 100px; margin-left: 10px"
                v-if="scope.row.is_new_field == 1"
                v-model="scope.row['field_description1']"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="content" v-if="currentIndex > 1">
        <div class="con-result">
          <div>
            <i class="el-icon-circle-check" style="color: green"></i>
            导入成功 {{ importResult.success_count }} 条
          </div>
          <div>
            <i style="color: red" class="el-icon-circle-close"></i>
            导入失败 {{ importResult.failed_count }} 条
          </div>
          <div style="padding-left: 20px; line-height: 18px">
            <ul>
              <li v-for="(item, index) in importResult.data" :key="index">
                {{ item }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </el-form>
    <div class="dialog-footer" style="text-align: center; padding: 20px 0">
      <el-button @click="handleCloseDialog">关闭</el-button>
      <el-button v-if="currentIndex === 1" type="primary" @click="handlePrev"
        >上一步</el-button
      >
      <el-button
        v-if="currentIndex === 0 || currentIndex === 1"
        :loading="nextLoading"
        type="primary"
        @click="handleClickSubmit()"
        >下一步</el-button
      >
    </div>
  </div>
</template>

<script>
import UploadLink from "@/components/uploadFile/uploadLink.vue";
import { dataFieldMapping, dataFieldImport } from "@/api/companymanagement";

export default {
  name: "datatransfer",
  components: { UploadLink },
  props: [],
  data() {
    return {
      currentIndex: 0,
      typeData: [
        {
          label: "运单",
          val: "1",
        },
        {
          label: "发货人",
          val: "2",
        },
        {
          label: "收货人",
          val: "3",
        },
        {
          label: "承运商",
          val: "4",
        },
        {
          label: "司机",
          val: "5",
        },
        {
          label: "车辆",
          val: "6",
        },
        {
          label: "温度计",
          val: "7",
        },
        {
          label: "路由",
          val: "8",
        },
        {
          label: "客户",
          val: "9",
        },
        {
          label: "账号",
          val: "10",
        },
      ],
      ruleForm: {
        data_type: "",
        file_url: [],
      },
      tableData: {},
      importResult: {
        data: [],
      },
      rules: {
        data_type: [
          { required: true, message: "请选择数据类型", trigger: "change" },
        ],
        file_url: [
          { required: true, message: "请导入文件", trigger: "change" },
        ],
      },
      nextLoading: false,
    };
  },
  watch: {
    "ruleForm.file_url": function (val) {
      this.$refs.imgRef1.clearValidate();
    },
  },
  computed: {
    usedNames() {
      return this.tableData.match_result.map((item) => {
        if (item.field_name) {
          return item.field_name;
        }
      });
    },
  },
  mounted() {
    const { type } = this.$route.query;
    // console.log(type,this.$route)
    if (type) {
      this.ruleForm.data_type = type * 1;
    }
  },
  methods: {
    handleCloseDialog() {
      this.$router.go(-1);
    },
    handleExceed(_, fileList) {
      this.$message.warning(`只能选择 ${fileList.length} 个文件上传`);
    },
    handlePrev() {
      this.currentIndex = 0;
    },
    handleChangeUseNew(val, row) {
      // console.log(val, '0000000');
      if (val === 1) {
        row.field_name = "";
        row.disableSelect = true;
      } else {
        row.disableSelect = false;
      }
    },
    handleClickSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        let _ruleForm = {
          ...this.ruleForm,
          file_url: this.ruleForm.file_url[0].url.replace(
            "https://dus-company-log-img.oss-cn-beijing.aliyuncs.com/",
            ""
          ),
        };
        if (this.currentIndex == 0) {
          this.nextLoading = true;
          dataFieldMapping(_ruleForm).then((res) => {
            if ((res || {}).code === 10000) {
              this.tableData = res.data.data;
              this.currentIndex = 1;
            }
            this.nextLoading = false;
          });
        }
        if (this.currentIndex == 1) {
          this.nextLoading = true;
          const _matchResult = [...this.tableData.match_result];
          _matchResult.forEach((item) => {
            if (item.is_new_field === 1) {
              item.field_description = item.field_description1;
              delete item.field_description1;
            }
            delete item.disableSelect;
          });
          dataFieldImport({
            ..._ruleForm,
            match_result: _matchResult,
            local_fields: this.tableData.local_fields,
          }).then((res) => {
            if ((res || {}).code === 10000) {
              this.importResult = res.data;
              this.currentIndex = 3;
            }
            this.nextLoading = false;
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.data-transfer-wrapper {
  background: #fff;
  // min-height: 100vh;
  padding: 10px;
  margin-top: 5px;
  margin-left: 5px;
  background-color: #fff;

  // display: flex;
  // justify-content: center;
  // flex-direction: column;
  // align-items: center;
  .transfer-step {
    width: 500px;
    margin: 30px auto 0;
    // margin-left: 100px;
    padding-left: 70px;
  }

  .transfer-form {
    width: 500px;
    margin: 0 auto;
  }

  .content {
    padding: 40px 0;
  }

  .con-result {
    width: 400px;
    min-height: 300px;
    background-color: #f7f7f7;
    border-radius: 5px;
    margin-left: 40px;
    padding: 20px;
    box-sizing: border-box;
    font-size: 14px;
    line-height: 26px;
  }
}
</style>